/*
核心Three.js初始化模块
负责场景、相机、渲染器的设置，以及WebXR配置
专为VR钓鱼游戏优化
*/

import * as THREE from 'three';
import * as ThreeMeshUI from 'three-mesh-ui';
import { VRButton } from './VRButton.js';
import { PicoVRConfig } from './PicoVRConfig.js';

// 创建场景
const scene = new THREE.Scene();
// 设置天蓝色背景，营造湖泊氛围
scene.background = new THREE.Color(0x87CEEB); // 天蓝色背景

// 创建相机
const width = window.innerWidth;
const height = window.innerHeight;

const camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000);
camera.position.set(0, 1.6, 5); // 钓鱼位置
camera.lookAt(0, 0, 0);

// 创建渲染器，启用WebXR
const renderer = new THREE.WebGLRenderer({ 
  antialias: true, // 钓鱼游戏启用抗锯齿以获得更好的视觉效果
  alpha: false,
  preserveDrawingBuffer: true,
  powerPreference: 'high-performance',
  precision: 'highp' // 钓鱼游戏使用高精度以支持水面反射
});

renderer.setSize(window.innerWidth, window.innerHeight);
renderer.xr.enabled = true;
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true; // 启用阴影以增强视觉效果
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMappingExposure = 1.0;

// 启用水面反射和粒子效果
renderer.capabilities.isWebGL2 = true;

// Pico VR特定的渲染器优化
if (renderer.xr.setFramebufferScaleFactor) {
  renderer.xr.setFramebufferScaleFactor(0.9); // 钓鱼游戏需要更高的分辨率
}

// 启用凹面渲染（如果支持）
if (renderer.xr.setFoveation) {
  renderer.xr.setFoveation(0.3); // 降低凹面渲染强度以保持细节
}

// 设置渲染器的样式
renderer.domElement.style.position = 'absolute';
renderer.domElement.style.top = '0';
renderer.domElement.style.left = '0';
renderer.domElement.style.zIndex = '1';

// 添加环境光照
const ambientLight = new THREE.AmbientLight(0x87CEEB, 0.4); // 柔和的天蓝色环境光
scene.add(ambientLight);

// 添加主光源（太阳光）
const directionalLight = new THREE.DirectionalLight(0xFFFFE0, 0.8);
directionalLight.position.set(50, 100, 50);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 500;
directionalLight.shadow.camera.left = -100;
directionalLight.shadow.camera.right = 100;
directionalLight.shadow.camera.top = 100;
directionalLight.shadow.camera.bottom = -100;
scene.add(directionalLight);

// 初始化Pico VR配置
async function initPicoVR() {
  try {
    const isPico = await PicoVRConfig.detectPicoDevice();
    if (isPico) {
      console.log('🎣 检测到Pico VR设备，启用钓鱼优化');
      PicoVRConfig.logDeviceInfo();
    } else {
      console.log('🖥️ 检测到非Pico设备，使用标准模式');
    }
  } catch (error) {
    console.warn('⚠️ Pico设备检测失败:', error);
  }
}

// 添加VR按钮和渲染器到DOM
document.body.appendChild(VRButton.createButton(renderer));
document.body.appendChild(renderer.domElement);

// 窗口大小调整处理
window.addEventListener('resize', function () {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

// 渲染循环回调数组
const loopCallbacks = [];

// 设置渲染循环
renderer.setAnimationLoop(loop);

let lastTime = 0;
let waterTime = 0; // 水面动画时间

function loop(elapsedTime) {
  // 帧率控制
  const delta = Math.min(elapsedTime - lastTime, 100) / 1000;
  lastTime = elapsedTime;
  waterTime += delta;

  // 检测VR模式
  const isVRMode = renderer.xr.isPresenting;

  // 非VR模式下的相机动画 - 钓鱼视角
  if (!isVRMode) {
    // 轻微的摇摆效果，模拟湖边的宁静感
    camera.position.x = 0.2 * Math.sin(elapsedTime * 0.0003);
    camera.position.y = 1.6 + 0.05 * Math.sin(elapsedTime * 0.0005);
    camera.lookAt(
      0.1 * Math.sin(elapsedTime * 0.0002),
      -0.5,
      -3
    );
  } else {
    // VR模式下的处理
    camera.position.set(0, 1.6, 5);
    
    // VR模式下的性能优化
    if (renderer.xr.setFramebufferScaleFactor) {
      renderer.xr.setFramebufferScaleFactor(0.8);
    }
  }

  // 更新Three-Mesh-UI
  ThreeMeshUI.update();

  // 执行所有注册的更新函数
  loopCallbacks.forEach(fn => fn(delta, waterTime));

  // 渲染场景
  renderer.render(scene, camera);
}

// 隐藏加载提示
function hideLoading() {
  const loading = document.querySelector('.loading');
  if (loading) {
    loading.style.opacity = '0';
    loading.style.transition = 'opacity 0.5s ease';
    setTimeout(() => {
      if (loading.parentNode) {
        loading.parentNode.removeChild(loading);
      }
    }, 500);
  }
}

// 显示非VR模式提示
function showNonVRHint() {
  const hint = document.createElement('div');
  hint.style.cssText = `
    position: fixed;
    top: 20px;
    left: 20px;
    background: rgba(46, 139, 87, 0.9);
    color: white;
    padding: 15px 20px;
    border-radius: 10px;
    font: 14px 'Microsoft YaHei', Arial, sans-serif;
    z-index: 998;
    max-width: 300px;
    line-height: 1.4;
    border: 2px solid #2E8B57;
  `;
  hint.innerHTML = `
    <div style="font-weight: bold; margin-bottom: 8px;">🎣 非VR模式</div>
    <div style="font-size: 12px;">
      • 鼠标控制视角<br>
      • WASD移动<br>
      • 点击进行钓鱼操作<br>
      • 建议使用VR设备获得最佳体验
    </div>
  `;
  document.body.appendChild(hint);
  
  // 10秒后自动隐藏
  setTimeout(() => {
    if (hint.parentNode) {
      hint.style.opacity = '0';
      hint.style.transition = 'opacity 0.5s ease';
      setTimeout(() => {
        if (hint.parentNode) {
          hint.parentNode.removeChild(hint);
        }
      }, 500);
    }
  }, 10000);
}

// 初始化
initPicoVR();

// 导出核心对象
export { scene, camera, renderer, loopCallbacks, hideLoading, showNonVRHint }; 